package com.example.audiorecord.ui;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.example.audiorecord.R;
import com.example.audiorecord.audiotools.AudioRecorder;
import com.example.audiorecord.audiotools.RecordStreamListener;
import com.example.audiorecord.customview.VadView;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 录音页面
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener, RecordStreamListener {

    private Button stopBtn, playOrPauseBtn;
    private ImageButton backBtn;
    private AudioRecorder audioRecorder;
    private boolean AUDIO_STATUS = false;
    private Chronometer chronometer;
    private TextView statusText;
    private long recordingTime;
    private VadView waveView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initAudioRecorder();

        //开始录音
        startAudioRecorder();
    }

    private void initView() {
        //实例化控件
        stopBtn = findViewById(R.id.stop_btn);
        playOrPauseBtn = findViewById(R.id.play_or_pause_btn);
        backBtn = findViewById(R.id.back_btn);
        chronometer = findViewById(R.id.my_chronometer);
        statusText = findViewById(R.id.status_text);
        waveView = findViewById(R.id.wave_vad);

        backBtn.setOnClickListener(this::onClick);
        stopBtn.setOnClickListener(this::onClick);
        playOrPauseBtn.setOnClickListener(this::onClick);
        chronometer.setBase(SystemClock.elapsedRealtime());
    }

    /**
     * 初始化audioRecorder
     */
    private void initAudioRecorder() {
        audioRecorder = AudioRecorder.getInstance();
    }

    //开始录音
    private void startAudioRecorder() {
        try {
            if (audioRecorder.getStatus() == AudioRecorder.Status.STATUS_NO_READY) {
                //初始化录音
                AUDIO_STATUS = true;
                String fileName = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
                audioRecorder.createDefaultAudio(fileName);
                audioRecorder.startRecord(this::recordOfByte);
                playOrPauseBtn.setBackgroundResource(R.drawable.pause_btn_icon);
                chronometer.setBase(SystemClock.elapsedRealtime() - recordingTime);
                chronometer.start();
                statusText.setText("Recording...");

            } else {
                audioRecorder.stopRecord();
                playOrPauseBtn.setBackgroundResource(R.drawable.start_btn_icon);
            }

        } catch (IllegalStateException e) {
            Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
        }

    }

    //暂停录音
    private void pauseAudioRecorder() {
        try {
            if (audioRecorder.getStatus() == AudioRecorder.Status.STATUS_START) {
                //暂停录音
                AUDIO_STATUS = false;
                audioRecorder.pauseRecord();
                playOrPauseBtn.setBackgroundResource(R.drawable.start_btn_icon);
                statusText.setText("Pause");
                chronometer.stop();
                recordingTime = SystemClock.elapsedRealtime() - chronometer.getBase();

            } else {
                audioRecorder.startRecord(null);
                playOrPauseBtn.setBackgroundResource(R.drawable.pause_btn_icon);
            }
        } catch (IllegalStateException e) {
            Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    //停止录音
    private void stopAudioRecorder() {
        audioRecorder.stopRecord();
        playOrPauseBtn.setBackgroundResource(R.drawable.start_btn_icon);
        chronometer.stop();
        AUDIO_STATUS = false;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            /**
             * 停止录音的点击事件
             * @param view
             */
            case R.id.stop_btn: {
                stopAudioRecorder();
                finish();
                break;
            }
            /**
             * 开始录音和暂停录音的点击事件
             * @param view
             */
            case R.id.play_or_pause_btn: {
                if (!AUDIO_STATUS) {
                    startAudioRecorder();
                } else {
                    pauseAudioRecorder();
                }

                break;
            }
            /**
             * 返回上一个页面
             */
            case R.id.back_btn: {
                finish();
                break;
            }
            default:
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (audioRecorder.getStatus() == AudioRecorder.Status.STATUS_START) {
            audioRecorder.pauseRecord();
            playOrPauseBtn.setBackgroundResource(R.drawable.start_btn_icon);
        }

    }


    @Override
    protected void onDestroy() {
        //页面关闭释放audioRecorder
        audioRecorder.release();
        //停止计时器
        chronometer.stop();
        super.onDestroy();

    }

    @Override
    public void recordOfByte(byte[] data, int begin, int end) {
        waveView.setAudio(toShortArray(data));
        waveView.refresh();
    }

    //byte数组转short数组
    public short[] toShortArray(byte[] src) {
        int count = src.length >> 1;
         short[] dest = new short[16000 * 12];
        for (int i = 0; i < count; i++) {
            dest[i] = (short) ((src[i * 2] & 0xff) | ((src[2 * i + 1] & 0xff) << 8)*2);
        }
        return dest;
    }

    public static byte[] int2Bytes(int value, int len) {
        byte[] b = new byte[len];
        for (int i = 0; i < len; i++) {
            b[len - i - 1] = (byte)((value >> 8 * i) & 0xff);
        }
        return b;
    }

}